/**
 * Description: class definition of HWSOAP, this class is core to communicate to the server
 * Copyright:  Copyright (c) 2003
 * Company: heweisoft
 * @author ly
 * @version 4.0
 * $Revision: 1.11.22.2 $
 * $Author: chenshuanghong $
 * $Date: 2018/06/14 01:15:03 $
 */
function HWSOAP(service, comp) {
	if (service.indexOf(".json") != -1) {
		if (service.substring(0, 1) == ".") {
			if (!comp) return;
			service = comp.getAbsolutePath(service);
		}
		this.__service = service;
		return;
	}
	if (service.substring(0, 1) == ".")
		service = service.substring(1);
	this.__service = service;
}

HWSOAP.prototype.send = function (oData, bAsync, oCallBack, oFailBack) {
	if (typeof(bAsync) == "undefined" || bAsync == null) {
		bAsync = false;
	}
	if (this.__service == null) 
		throw new Error(0,"ERROR:You must specify the soap service.");
//    this.findSpectialCharacter(null,oData);//检测特殊字符,解决SQL 盲注的安全BUG
	var othis = this;

	$.ajax({
 		url:this.__service,
	    type:'post', //数据发送方式
	    async:bAsync,
	   	dataType:'json',
	    data:oData,
	    timeout: 100000,     //设置本地超时 .( 毫秒)
	    error: function(sError){
			var errorStr = sError.responseText;
            othis.showError(errorStr);
            if (oFailBack) {
                oFailBack(sError);
            }
	    },
	    success: function(oResult){
            if (oResult.errNo) {
                othis.showError(oResult.errDetail);
            }
	  		othis.__result =  oResult;
	  		if (bAsync && oCallBack) {
	  			oCallBack(oResult);
	  		}
	    }
	});
}
/**
 * 检测是否有特殊字符，可递归调用
 * @param o
 */
HWSOAP.prototype.findSpectialCharacter=function(k,o){
    if(typeof(o)==="object"){
        for(var s in o){
            this.findSpectialCharacter(s,o[s]);
        }
    }else if(typeof(o)==="function"){
        //什么也不做
    }else{
        //统一对特殊字符进行检测
        var vkeyWords=/[|&;$%@'<>\(\)+]/g;//检测的特殊字符项：分组：[1] |（竖线符号） [2] & （& 符号）[3];（分号）[4] $（美元符号）[5] %（百分比符号）
        //                        [6] @（at 符号）[7] '（单引号）   [8] "（引号）[9] \'（反斜杠转义单引号） [10] \"（反斜杠转义引号）
        //                        [11] <>（尖括号）[12] ()（括号）[13] +（加号）[14] CR（回车符，ASCII 0x0d）[15] LF（换行，ASCII 0x0a）
        //                        [16] ,（逗号）[17] \（反斜杠）
        //                        说明：双引号不能过滤，逗号也不能过滤，保存工作台数据时有\"，“,和逗号回车和换行也不能过滤，反斜杠也不能过滤
        if(vkeyWords.test(o)){
            throw new Error(0,"输入的信息当中有特殊字符，请检查:key:"+k+";value:"+o);
        }
    }
}
HWSOAP.prototype.sendb = function (oData, bAsync, oCallBack, oFailBack) {
    if (typeof(bAsync) == "undefined" || bAsync == null) {
        bAsync = false;
    }
    if (this.__service == null)
        throw new Error(0,"ERROR:You must specify the soap service.");

    var othis = this;
    $.ajax({
        url:this.__service,
        type:'post', //数据发送方式
        async:bAsync,
        dataType:'json',
        data:JSON.stringify(oData),
        contentType: "application/json",
        timeout: 100000,     //设置本地超时 .( 毫秒)
        error: function(sError){
            var errorStr = sError.responseText;
            othis.showError(errorStr);
            if (oFailBack) {
                oFailBack(sError);
            }
        },
        success: function(oResult){
        	if (oResult.errNo) {
                othis.showError(oResult.errDetail);
            }
            othis.__result =  oResult;
            if (bAsync && oCallBack) {
                oCallBack(oResult);
            }
        }
    });
}

HWSOAP.prototype.getResult = function () {
	return this.__result;
}

HWSOAP.prototype.showError = function (errorStr) {
    if (errorStr){
    	var startIndex = errorStr.indexOf("<body>");
    	var endIndex = errorStr.indexOf("</body>");
    	if(startIndex != -1 && endIndex != -1){
    		errorStr = "<div style='margin-top:10px;font-weight:bold'><span>系统发生错误。</span><a  style='cursor:pointer' onclick='showMoreInfo(this)'>点击查看详情</a>" +
    				"</div><div style='display:none' id='info'>"+errorStr.substring(startIndex+6,endIndex) +"</div>";
    	}
        WinUtil.showMessage({type:"error",html:errorStr,time:30000});
    }
    if (errorStr == null){
        return;
    }
    this._alert = false;
    if (errorStr.indexOf("会话已经过期") != -1
        || errorStr.indexOf("系统会话已经过期") != -1
        || errorStr.indexOf("找不到在线用户信息!") != -1
        || errorStr.indexOf("找不到当前在线用户信息") != -1) {
    	if (this._alert == false) {
    		alert("系统会话已经失效, 请重新登录!");
        	this._alert = true;
    	}
    	window.top.location.href = "/";
    }
}

HWSOAP.getJSONData = function(sPath, oCompPath) {
	if (sPath.substring(0, 1) == ".") {
        sPath = oCompPath.substring(0, oCompPath.lastIndexOf("/")) + sPath.substring(1);
    }
    var soap = new HWSOAP(sPath);
    soap.send({});
    return soap.getResult();
}


/**
 * 异步加载json数据
 */
HWSOAP.getJSONDataAsync = function(sPath, oCallBack) {
	if (sPath.substring(0, 1) == ".") {
        sPath = oCompPath.substring(0, oCompPath.lastIndexOf("/")) + sPath.substring(1);
    }
    var soap = new HWSOAP(sPath);
    soap.send({}, true, function(oResult) {
    	oCallBack(oResult);
    });
}
function showMoreInfo(evt){
	$("#info",evt.parentNode.parentNode).toggle();
}



/**
 * 3.0中的hwsoap请求
 */
function HWSOAP2(service,sAction,sParams,sDataXML) {
    if(g_test && typeof sAction!="undefined") {
        sAction = modifyAction(sAction);
    }    

	//private property definition
	if(!isMozilla) {
        try{
    	    this.__xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");
        }
        catch (e){
            alert("IE purview has been set too strict.Tool-->Internet Option-->Safe-->Bilievable Site.Bring up ActiveX ");
            return;
        }
	} else {
		this.__xmlhttp = new XMLHttpRequest();		
	}
	this.__service = service;
	this.__sent = false;

	this.loaded = true;

	if (sAction!=null) {
		this.__requests = new Array(new Array(sAction,sParams,sDataXML));
	} else 
		this.__requests = new Array();

	//property indicate a soap send is successful and return a valid xml 
	this.success = false;
	//property indicate although it is success but some request is error.
	this.hasErorr = false;
	//property to store the onload event handler
	this.onload = null;
		this.bXML = true;
}

HWSOAP2.prototype.XMLHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";

HWSOAP2.prototype.addRequest = function (sAction,sParams,sDataXML) {
    if(g_test && typeof sAction!="undefined") {
        sAction = modifyAction(sAction);
    }    
    
	if (!this.loaded) return;
	
	if (this.__sent) {
		__SOAP_ResetObject(this);
	}
	this.__requests[this.__requests.length] = new Array(sAction,sParams,sDataXML);
}

HWSOAP2.prototype.send = function (sService,bAsync,oCallBack) {
	if (this.__sent) {
		throw new Error(0,"ERROR:you cann't call send twince.");
	} else {
		if (sService != null) {
			this.__service = sService;
		}
		if (this.__service == null) 
			throw new Error(0,"ERROR:You must specify the soap service."); 
		this.loaded = false;
		if (bAsync==null) 
			bAsync = false;
		var req,reqs = this.__requests;
		var xmlhttp = this.__xmlhttp;
		var sXML = this.XMLHeader;
		sXML += "\n<hs>\n";
		var sAction="",sParams="",sData="";
		for (var i = 0; i< reqs.length; i++) {
			req = reqs[i];
			sXML += "<req>\n<ac>"+req[0]+"<\/ac>\n";
			if (req[1]!=null) 
				sXML += "<pm>\n"+req[1]+"\n<\/pm>\n";
			if (req[2]!=null) 
				sXML += "<da>\n"+req[2]+"\n<\/da>\n";
			sXML += "<\/req>\n";
		}
		sXML+="<\/hs>";

		var othis = this; 
		$.ajax({
     		url:this.__service,
		    type:'post', //数据发送方式 
		    async:false,
		   	dataType: 'xml',   // 注意这里是xml哦
		    data:sXML,   	   //要传递的数据 
		    timeout: 2000,     //设置本地超时 .( 毫秒)
		    error: function(xml){
				var errorStr = xml.responseText;
				othis.showError(errorStr);
		    },
		    success: function(xml){
		    	var oResult = $(xml).children("sr");
		  		othis.__results2 =  oResult;
		  		if (bAsync && oCallBack) {
		  			oCallBack(oResult);
		  		}
		    }
		});
	}
}

HWSOAP2.__asyncObjects = new Array();
HWSOAP2.prototype.setOnLoad = function (caller,handler) {
	var i,ao = HWSOAP2.__asyncObjects;
	for (i = 0; i<ao.length; i++) {
		if (null == ao[i]) break; 
	}
	ao[i] = new Array(this,caller,handler);
	this.onload = new Function("__SOAP_onsoapload("+i+");");
}

HWSOAP2.prototype.showError = function (errorStr) {
    if (errorStr){
    	var startIndex = errorStr.indexOf("<body>");
    	var endIndex = errorStr.indexOf("</body>");
    	if(startIndex != -1 && endIndex != -1){
    		errorStr = "<div style='margin-top:10px;font-weight:bold'><span>系统发生错误。</span><a  style='cursor:pointer' onclick='showMoreInfo(this)'>点击查看详情</a>" +
    				"</div><div style='display:none' id='info'>"+errorStr.substring(startIndex+6,endIndex) +"</div>";
    	}
        WinUtil.showMessage({type:"error",html:errorStr,time:30000});
    }
    if (errorStr == null){
        return;
    }
    this._alert = false;
    if (errorStr.indexOf("会话已经过期") != -1
        || errorStr.indexOf("系统会话已经过期") != -1
        || errorStr.indexOf("找不到在线用户信息!") != -1
        || errorStr.indexOf("找不到当前在线用户信息") != -1) {
    	if (this._alert == false) {
    		alert("系统会话已经失效, 请重新登录!");
        	this._alert = true;
    	}
    	window.top.location.href = "/";
    }
}

HWSOAP2.prototype.getResult = function (index) {
	if (index == null) index = 0;
	if(this.__results2){
		return this.__results2[index];
	}else{
		return null;
	}
	
}

function __SOAP_CheckResult(soap) {
	if (soap.bXML) {
	var nd = soap.__xmlhttp.responseXML;
	if (nd != null && nd.xml!="") {
		soap.success = true;
		//alert(nd.xml);
		var chd,chlist = nd.selectNodes("./sr/*");
		soap.__results = chlist;
		soap.hasError = nd.selectSingleNode("./sr/re")!=null;
	} else {
		soap.hasError = true;
	}
	} else {
		soap.__results = soap.__xmlhttp.responseText;
		soap.success = true;
		soap.hasError = false;
	}
}

/**
 * 本地存储数据
 * @param service 请求服务
 * @param oReq 请求数据
 * @param data 返回结果
 * @param bUpdate 强制更新,默认为false
 */
HWSOAP.addLocal = function(service, oReq, data, bUpdate) {
    var result  = localStorage.getItem(service + JSON.stringify(oReq));
    if (bUpdate) {
        localStorage.setItem(service + JSON.stringify(oReq), JSON.stringify(data));
    } else {
        if (!result) {
            localStorage.setItem(service + JSON.stringify(oReq), JSON.stringify(data));
        }
    }
}

/**
 * 访问本地存储
 * @param oData
 * @param bSync
 * @param oCallBack
 */
HWSOAP.prototype.local = function(oData, bSync, oCallBack) {
    var result = localStorage.getItem(this.__service + JSON.stringify(oData));
    if (result) result = JSON.parse(result);
    this.__result = result;
    if (oCallBack) {
        oCallBack(result);
    }
}